package mm.chensj.demo.ch01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Lenovo
 * @title
 * @project shiro-demo
 * @package mm.chensj.demo.ch01
 * @date: 2019-01-17 16:36
 */
public class ShiroLogin {

    private static final Logger logger = LoggerFactory.getLogger(ShiroLogin.class);
    public static void main(String[] args){
        // shiro 简单使用
        String iniName = "classpath:shiro.ini" ;
        String username = "zhang1" ;
        String password = "123" ;
        //login(iniName,username,password);
        // 使用jdbc
        iniName = "classpath:shiro-jdbc-realm.ini";
        login(iniName,username,password);
    }

    public static void login(String iniName,String username,String password){

        logger.info("ini-path:{}",iniName);
        //1、获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(iniName);
        //2、获取SecurityManager
        SecurityManager manager = factory.getInstance();
        //3、设置SecurityManager作为默认使用的
        SecurityUtils.setSecurityManager(manager);
        //4、获取Subject
        Subject subject = SecurityUtils.getSubject();
        //5、创建用户Token
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //6、登录用户
        try {
            subject.login(token);
        }catch (IncorrectCredentialsException incorrectCredentialsException){
            logger.error("用户名或密码输入错误:{}",incorrectCredentialsException.getMessage());
        }catch (UnknownAccountException unknownAccountException){
            logger.error("用户名不存在:{}",unknownAccountException.getMessage());
        }catch (AuthenticationException e){
            logger.error("认证其他错误:{}",e.getMessage());
            // 登录失败
        }
        logger.info("用户登录状态:{}",subject.isAuthenticated());
        // 退出当前用户
        subject.logout();
    }

}
